<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="新闻分类" prop="newsType">
        <el-cascader
          v-model="catQueryModel"
          :options="categoryList"
          :props="{ checkStrictly: true }"
          @change="handleCatQueryChange"></el-cascader>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="跳转类型" prop="urlType">
        <el-select v-model="queryParams.urlType" placeholder="请选择跳转类型  1 站内链接  2 外链 " clearable size="small">
          <el-option
            v-for="dict in dict.type.news_url_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户端" prop="showClient">
        <el-select v-model="queryParams.showClient" placeholder="请选择展示客户端" clearable size="small">
          <el-option
            v-for="dict in dict.type.news_show_client"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="投放区域" prop="allArea">
        <el-select v-model="queryParams.allArea" placeholder="请选择投放区域类型" clearable size="small" @change="allAreaChange">
          <el-option
            v-for="dict in dict.type.news_area_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域选择" prop="allArea" v-if="queryParams.allArea == 0">
        <el-cascader ref="cascaderAddr"
                     :props="{ checkStrictly: true }"
                     :options="areaTreeList"
                     :value="casValue"
                     :label="casLabel"
                     clearable
                     @change="handleSelectAreaChange"></el-cascader>
      </el-form-item>
      <el-form-item label="发布时间" prop="pubTime">
        <el-date-picker clearable size="small"
                        v-model="pubTimeRange"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:news:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          icon="el-icon-s-promotion"
          @click="handlePub"
          v-hasPermi="['cms:news:pub']"
        >发布</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cms:news:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="缩略图" align="center" prop="thumbnail" >
        <template slot-scope="scope">
          <el-image style="width: 50px" fit="contain" :src="scope.row.thumbnail"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="新闻分类" align="center" prop="catNamePath" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="发布时间" align="center" prop="pubTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pubTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转类型" align="center" prop="urlType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.news_url_type" :value="scope.row.urlType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户端" align="center" prop="showClient">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.news_show_client" :value="scope.row.showClient"/>
        </template>
      </el-table-column>
      <el-table-column label="投放区域" align="center" prop="province" >
        <template slot-scope="scope">
          <span v-if="scope.row.allArea == 1">全国</span>
          <span v-else>{{scope.row.province + ' '+ scope.row.city}}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cms:news:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handlePub(scope.row)"
            v-hasPermi="['cms:news:pub']"
          >发布</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cms:news:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="50%" @close="cancel" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新闻分类" prop="newsType">
              <el-cascader
                v-model="catModel"
                :options="categoryList"
                :props="{ checkStrictly: true }"
                @change="handleCatChange"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="投放区域" prop="allArea">
          <div class="allAreaDiv">
            <div class="allAreaSwitch">
              <el-switch
                style="display: block"
                v-model="form.allArea"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="不分区域"
                :active-value= "activeValue"
                :inactive-value= "inactiveValue"
                inactive-text="区域投放">
              </el-switch>
            </div>
            <div class="allAreaCas">
              <el-cascader v-if="form.allArea == 0"  ref="cascaderAddrForm"
                           v-model="casModel"
                           :props="{ checkStrictly: true }"
                           :options="areaTreeList"
                           :value="casValue"
                           :label="casLabel"
                           clearable
                           placeholder="请选择投放区域"
                           @change="handleAreaChange"></el-cascader>
            </div>
          </div>

        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="展示终端" prop="showClient">
              <el-select v-model="form.showClient" placeholder="请选择展示客户端"  style="width: 100%">
                <el-option
                  v-for="dict in dict.type.news_show_client"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转类型" prop="urlType" >
              <el-select v-model="form.urlType" placeholder="请选择跳转类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.news_url_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" v-if="form.urlType == 2">
          <editor v-model="form.content" v-if="editorOpen" :min-height="192"/>
        </el-form-item>
        <el-form-item label="简介" prop="briefIntro">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入简介"
            v-model="form.briefIntro"
            maxlength="300"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="pubTime">
              <el-date-picker clearable size="small"
                              v-model="form.pubTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="缩略图" prop="thumbnail">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12" v-if="form.urlType == 3 || form.urlType == 4 || form.urlType == 5">
            <el-form-item label="url" prop="url">
              <el-input v-model="form.url" placeholder="请输入url" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.urlType == 5">
            <el-form-item label="appid" prop="请输入appid" >
              <el-input v-model="form.appid" placeholder="请输入appid" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listNews, getNews, delNews, addNews, updateNews, pubNews} from "@/api/cms/news/news";
  import { cascadeCategory } from "@/api/cms/news/category";
  import { areaCascade} from "@/api/common/common";
  import Tinymce from '@/components/Tinymce/index'
  import defSet from '@/settings'
  import { mapGetters } from 'vuex'
  export default {
    name: "News",
    components: {
      'editor': Tinymce
    },
    dicts: ['news_show_client', 'news_url_type', 'sys_is_enable', 'news_type','news_area_type'],
    data() {
      return {
        editorOpen:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 新闻公告表格数据
        newsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          delFlag: 0,
          isEnable: 0,
          title: null,
          newsType: null,
          author: null,
          pubTime: null,
          urlType: null,
          showClient: null,
          provinceCode: null,
          cityCode: null,
          allArea: null,
          appid: null,
          catId: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          title: [
            { required: true, message: "标题不能为空", trigger: "blur" },
            { min: 1, max: 20, message: '标题长度必须介于 1 和 30 之间', trigger: 'blur' }
          ],
        },
        imgPre: defSet.imgPre,
        url:process.env.VUE_APP_BASE_API + '/common/oss/upload',
        imageUrl: '',
        casValue: 'value',
        casLabel: 'label',
        casModel: [],
        areaTreeList: [],//行政区划数组
        activeValue: 1,
        inactiveValue: 0,
        pubTimeRange:[],
        categoryList: [],
        catQueryModel: [],
        catModel: [],
      };
    },
    created() {
      this.getList();
      this.getAreaTree();
      this.getCascadeCategory()
    },
    computed: {
      ...mapGetters(['token']),
      headers() {
        return{
          "Authorization": this.token // 直接从本地获取token就行
        }
      }
    },
    methods: {
      getCascadeCategory() {
        cascadeCategory().then(response => {
          // this.categoryList = response.data;
          this.categoryList = this.handleTree(response.data, "value");
        });
      },
      getAreaTree() { // 获取省市县数据并将其分类
        areaCascade({level: 2}).then(response => {
          this.areaTreeList = response.data;
          this.loading = false;
        });
      },
      /** 查询新闻公告列表 */
      getList() {
        this.loading = true;
        let qParams = this.addPubDateRange(this.queryParams,this.pubTimeRange);
        listNews(qParams).then(response => {
          this.newsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      addPubDateRange(params, dateRange) {
        var search = params;
        search.pubTimeStart = "";
        search.pubTimeEnd = "";
        if (null != dateRange && '' != dateRange) {
          search.pubTimeStart = dateRange[0] + " 00:00:00";
          search.pubTimeEnd = dateRange[1] + " 23:59:59";
        }
        return search;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.editorOpen = false;
        this.imageUrl = '';
        this.casValue = [];
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          newsId: null,
          title: null,
          subTitle: null,
          newsType: null,
          content: null,
          briefIntro: null,
          author: null,
          pubTime: null,
          delFlag: 0,
          isEnable: 0,
          sort: null,
          thumbnail: null,
          url: null,
          urlType: 1,
          showClient: null,
          province: null,
          provinceCode: null,
          city: null,
          cityCode: null,
          allArea: 1,
          appid: null
        };
        this.resetForm("form");
        this.imageUrl = '';
        this.casModel = [];
        this.catModel = []
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.catQueryModel = [];
        this.queryParams.catId = null;
        this.pubTimeRange = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.newsId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.editorOpen = true;
        this.title = "添加新闻公告";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const newsId = row.newsId || this.ids
        getNews(newsId).then(response => {
          this.form = response.data;
          this.wrap(response.data)
          this.open = true;
          this.editorOpen = true;
          this.title = "修改新闻公告";
          this.imageUrl = this.form.thumbnail
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.newsId != null) {
              updateNews(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.editorOpen = false;
                this.imageUrl = '';
                this.casValue = [];
                this.getList();
              });
            } else {
              addNews(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.editorOpen = false;
                this.imageUrl = '';
                this.casValue = [];
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const newsIds = row.newsId || this.ids;
        this.$modal.confirm('是否确认删除？').then(function() {
          return delNews(newsIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },

      /** 发布按钮操作 */
      handlePub(row) {
        const newsIds = row.newsId || this.ids;
        this.$modal.confirm('是否确认发布？').then(function() {
          return pubNews(newsIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("发布成功");
        }).catch(() => {});
      },
      handleAvatarSuccess(res, file) {

        // this.imageUrl = URL.createObjectURL(file.raw);
        this.imageUrl = res.data.url;
        this.form.thumbnail = this.imageUrl;
      },
      beforeAvatarUpload(file) {
        const isType = file.type === 'image/jpeg' || file.type === 'image/png'  || file.type === 'image/jpg';
        const isLt = file.size / 1024 / 1024 < 2;
        if (!isType) {
          this.$message.error('封面图片只能是 JPG、PNG 格式!!');
        }
        if (!isLt) {
          this.$message.error('上传图片大小不能超过2M!');
        }
        return isType && isLt;
      },
      handleAreaChange(value) { // 表单内选中的省市县数据
        let len = value.length;
        var node = this.$refs['cascaderAddrForm'].getCheckedNodes()[0];
        var  thsAreaCode = node.pathLabels   //注意2： 获取label值
        if (len == 1){
          this.form.provinceCode = value[0];
          this.form.province = thsAreaCode[0];
          this.form.cityCode = undefined;
          this.form.city = undefined;
          this.form.adLevel = 1;
        }else if (len == 2){
          this.form.provinceCode = value[0];
          this.form.cityCode = value[1];
          this.form.province = thsAreaCode[0];
          this.form.city = thsAreaCode[1];
          this.form.adLevel = 2;
        }
      },
      handleSelectAreaChange(value) { // 选中省市县数据
        let len = value.length;
        this.queryParams.provinceCode = null;
        this.queryParams.cityCode = null;
        if (len == 1){
          this.queryParams.provinceCode = value[0];
        }else if (len == 2){
          this.queryParams.provinceCode = value[0];
          this.queryParams.cityCode = value[1];
        }
      },
      wrap(val) { // 选中省市县数据
        if (val.allArea == 0){
          if (val.adLevel == 1){
            this.casModel[0] = this.form.provinceCode;
          }else if(val.adLevel == 2){
            this.casModel[0] = this.form.provinceCode;
            this.casModel[1] = this.form.cityCode;
          }
        }
        this.catModel = []
        if (val.catPath){
          this.catModel = val.catPath.split(",")
        }
      },
      /** 投放区域选择事件 */
      allAreaChange(val){
        console.log('val: ' + val )
        if (val == 1){
          this.queryParams.provinceCode = undefined;
          this.queryParams.cityCode = undefined;
        }
      },
      /** 分类级联表单查询选中事件 */
      handleCatQueryChange(value) { // 表单内选中的省市县数据
        let len = value.length;
        if (len > 0){
          this.queryParams.catId = value[len -1];
        }else{
          this.queryParams.catId = null;
        }
      },
      /** 分类级联表单选中事件 */
      handleCatChange(value) { // 表单内选中的省市县数据
        console.log(value);
        let len = value.length;
        if (len > 0){
          this.form.catId = value[len -1];
        }else{
          this.form.catId = null;
        }
      },
    }
  };
</script>
<style lang="less" scoped>

.avatar-uploader {
  /deep/.el-upload {
    border: 1px dashed #df2727;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.allAreaDiv{
  display: flex;
}
.allAreaDiv .allAreaSwitch{
  flex: 1;
  max-width: 200px;
  margin-top: 5px;
}
.allAreaSwitch .allAreaCas{
  flex: 1;
}
</style>
